const express = require('express');
const router = express.Router();
const db = require('../db/mysqlConfig');

// 提交评价
router.post('/api/review/submit', (req, res) => {
    const { user_id, room_id, rating, text_review, images } = req.body;

    // 验证必填字段
    if (!user_id || !room_id || !rating || !text_review) {
        return res.status(400).json({ code: '1', data: { message: '缺少必要参数' } });
    }

    if (rating < 1 || rating > 5) {
        return res.status(400).json({ code: '1', data: { message: '评分必须在1到5之间' } });
    }

    if (text_review.length > 200) {
        return res.status(400).json({ code: '1', data: { message: '评价内容不能超过200字' } });
    }

    const insertSql = `
        INSERT INTO user_reviews (user_id, room_id, rating, text_review, images, created_time)
        VALUES (?, ?, ?, ?, ?, NOW())
    `;

    const imagesJson = images ? JSON.stringify(images) : null;

    db.query(insertSql, [user_id, room_id, rating, text_review, imagesJson], (error, result) => {
        if (error) {
            return res.status(500).json({ code: '1', data: { message: '评价提交失败', error } });
        }

        // 构建返回对象
        const newReview = {
            review_id: result.insertId,
            user_id,
            room_id,
            rating,
            text_review,
            images: images || [],
            created_time: new Date().toISOString()
        };

        res.json({ code: '0', data: { message: '评价提交成功', review: newReview } });
    });
});

module.exports = router;
